import 'package:flutter/material.dart';
import '../../res/list_data.dart';

class GridViewPage extends StatelessWidget {
  const GridViewPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GridView'),
      ),
      body: HomePage(),
    );
  }
}

//使用SliverGridDelegateWithFixedCrossAxisCount
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  Widget _initGridViewData(context, index) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/animated7', arguments: {
          "imageUrl": listData[index]["imageUrl"],
          "title": listData[index]["title"],
          "index": index,
        });
      },
      child: Container(
        decoration: BoxDecoration(border: Border.all(color: Colors.teal)),
        child: Column(
          children: [
            Expanded(// Expanded填充剩余空间
              child: Hero(
                tag: listData[index]["imageUrl"],
                child: Image.network(
                  listData[index]["imageUrl"],
                  fit: BoxFit.cover, // 保持图片比例，填充容器
                  width: double.infinity, // 宽度填满
                ),
              ),
            ),
            const SizedBox(height: 10),
            //Text(listData[index]["title"], style: const TextStyle(fontSize: 18)),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                listData[index]["title"],
                style: const TextStyle(fontSize: 18),
                maxLines: 1, // 限制行数
                overflow: TextOverflow.ellipsis, // 超出显示省略号
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: EdgeInsets.all(10),
      itemCount: listData.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( // 使用SliverGridDelegateWithFixedCrossAxisCount
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        crossAxisCount: 2,
        childAspectRatio: 1,
      ),
      itemBuilder: _initGridViewData,
    );
  }
}
